package com.ciwong.epaper.modules.cordva.html;

import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.cordva.bean.GetViedoRequestParms;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.eventbus.EventBus;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.google.gson.Gson;

import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by young on 2016/11/10.
 * 新的视频讲解页面
 */
public class NewVideoExplationActivity extends BaseHtmlActicity {

    private String mTeacherComment;
    private String currenttitle;
    private long level = -1;
    //资源JSON
    private String result;
    private int mServiceId;
    private String productId;


    private Context mContext;
    /**
     * 扫一扫数据所属的服务列表
     */
    private EApplication eApplication;

    private Module mModule;
    private int position;
    private String mJsonResPath;
    private DownLoadInfo mDownLoadInfo;
    private EpaperInfo mEpaperInfo;
    //扫一扫  作业页面拿不到学科ID 目前默认为1
    private int subjectId = 1;
    private String cId;
    private String classId;

    private boolean isInd = true;

    //标题
    private RelativeLayout topLin;
    private TextView titleText;
    private ImageView backIma;

    @Override
    protected void init() {
        super.init();
        setGoBackListener(this);
        eApplication = (EApplication) getApplication();
        mContext = this;
        FileUtil.CheckNewViedoHtmlExists(NewVideoExplationActivity.this);
        SystemWebViewClient systemWebViewClient = new SystemWebViewClient(systemWebViewEngine) {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("beian.miit.gov.cn")
                        || url.contains("www.beian.gov.cn")
                    ) {
                    return true;
                }
                WebView.HitTestResult hitTestResult = view.getHitTestResult();
                //WebView hitTestResult==null解决重定向问题
                if (!TextUtils.isEmpty(url) && hitTestResult == null) {
                    view.loadUrl(url);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
            @Override
            public void onReceivedError(WebView webView, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(webView, request, error);

                if (webView != null && no_net_work != null) {
//                    webView.setVisibility(View.GONE);
//                    no_net_work.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);

            }
        };
        webView.setWebViewClient(systemWebViewClient);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int setView() {
        return R.layout.new_video_html;
    }

    @Override
    protected void findViews() {
        backIma = (ImageView) findViewById(R.id.back_img);
        findViewById(R.id.activity_base_titlebar).setVisibility(View.GONE);
        topLin = (RelativeLayout) findViewById(R.id.top_rel);
        titleText = (TextView) findViewById(R.id.title_center_cur);
        super.findViews();

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        final int scr_hei = dm.heightPixels / 2;
        webView.setScrollViewListener(new SystemWebView.ScrollViewListener() {
            //用于标题的显示隐藏
            @Override
            public void onScrollChanged(int x, int y, int oldx, int oldy) {
                //通过标题的y坐标来判断
                if (isInd) {
                    if (y >= scr_hei) {

                        backIma.setImageResource(R.mipmap.back_book);
                        topLin.setBackgroundColor(NewVideoExplationActivity.this.getResources().getColor(R.color.color_light_green));
                        titleText.setVisibility(View.VISIBLE);
                    } else {
                        backIma.setImageResource(R.mipmap.v_back);
                        topLin.setBackgroundColor(NewVideoExplationActivity.this.getResources().getColor(R.color.transparent));
                        titleText.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });

    }

    @Override
    protected void initEvent() {
        backIma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
    }

    /**
     * 是否来自资源预览
     */
    boolean isPreView;

    @Override
    protected void loadData() {
        try{
            super.loadData();
            Intent intent = getIntent();
            mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            mEpaperInfo = (EpaperInfo) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_EPAPER_INFO);
            if(mDownLoadInfo!=null&&mDownLoadInfo.getType()==1){//new resourse  type
                currenttitle = mDownLoadInfo.getResourceName();
                if (null != mEpaperInfo) {
                    subjectId = mEpaperInfo.getSubjectId();//扫一扫书柜
                }else {
                    subjectId = mDownLoadInfo.getSubjectId();//扫一扫章节
                }
//                subjectId = mEpaperInfo.getSubjectId();
            }else {
                currenttitle = intent.getStringExtra(IntentFlag.INTENT_FLAG_SERVICE_TITLE);

                if (null != mEpaperInfo) {
                    subjectId = mEpaperInfo.getSubjectId();
                }
            }


            //服务id 用于作业提交，权限判断等

            isPreView = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_PRE_VIEW, false);
            if (isPreView) {
                mServiceId = 1;
            } else {
                mServiceId = intent.getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, 0);
            }
            mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            position = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
            classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
            if (classId == null && eApplication.getClazz() != null) {
                classId = String.valueOf(eApplication.getClazz().getClassId());
            }

            if (null != mDownLoadInfo) {
                productId = mDownLoadInfo.getBookId();
            }

            if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
                mJsonResPath = ESystem.getPackagesJsonPathNew(mDownLoadInfo.getBookId(),mDownLoadInfo.getChapterId(),mDownLoadInfo.getModuleId(),mDownLoadInfo.getVersionId());
                cId = mDownLoadInfo.getChapterId();
            }else {
                if (null != mModule && position < mModule.getResourceList().size()) {
                    mJsonResPath = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
                    cId = mModule.getModuleInfo().getcId();
                }

            }




            setTitleText(currenttitle);
            //在此保存提交答案所需信息
            mTeacherComment = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TEACHER_COMMENT);
            setStartURL("file://" + ESystem.getVideoEXPath() + File.separator + "newVideo.html");
            loadUrl(startURL.toString());
            initTeacherComment();

        }catch (Exception e){
            e.getStackTrace();
        }

    }

    //老师点评接口
    private void initTeacherComment() {
        {
            if (null != mTeacherComment && mTeacherComment.length() > 0) {
                setRightBtnBG(R.mipmap.icon_teacher_comment);
                setRightBtnEnable(true);
                setRightBtnListener(new ViewOnClickListener() {
                    @Override
                    public void avertRepeatOnClick(View v) {
                        DialogUtil.showCommentDialog(NewVideoExplationActivity.this, mTeacherComment);
                    }
                });
            }
        }
    }


    /**
     * eventBus 回调方法
     *
     * @param submitEvent
     */
    public void onEventMainThread(SubmitEvent submitEvent) {

        //新的html5 只需要打开视频跟获取资源文件,新的视频讲解不提交，所以没有记录，记录都是以前的，
        // 兼容只需要在打开视频页面区别是记录播放视频还是新的视频讲解，打开视频加参数即可

        final String id = submitEvent.getId();
        if ("SetTitle".equals(id)) {
            isInd = true;
            try {
                String arg = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(arg);
                if (jsonObject.has("title")) {
                    currenttitle = jsonObject.getString("title");
                }
                if (jsonObject.has("level")) {
                    level = jsonObject.getLong("level");
                }
                //改变Title 方法
                if (titleText != null) {
                    titleText.setText(currenttitle);
                    titleText.setVisibility(View.INVISIBLE);
                    if (currenttitle.equals("课程介绍")) {
                        isInd = false;
                        topLin.setBackgroundColor(NewVideoExplationActivity.this.getResources().getColor(R.color.color_light_green));
                        titleText.setVisibility(View.VISIBLE);
                    } else {
                        topLin.setBackgroundColor(NewVideoExplationActivity.this.getResources().getColor(R.color.transparent));
                    }
                }
            } catch (Exception e) {
                e.getStackTrace();
            }

        }  else if ("GetJsonData".equals(id)) {//获取视频讲解题目资源数据
            try {
                String callbackID = submitEvent.getCallbackId();
                String arg = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(arg);
                int source = -1;
                if (jsonObject.has("source")) {
                    source = jsonObject.getInt("source");
                }
                //2 视频讲解
                if (source == 2 && callbackID != null && mJsonResPath != null) {
                    getResultRes(mJsonResPath, callbackID);
                }

            } catch (Exception e) {
                e.getStackTrace();
            }

        } else if ("GetVideoList".equals(id)) {//获取试卷视频列表

            try {
                String callbackID = submitEvent.getCallbackId();
                String arg = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(arg);
                int source = -1;

                if (jsonObject.has("source")) {
                    source = jsonObject.getInt("source");
                }
                //2 视频讲解
                if (source == 2 && callbackID != null) {
                }

            } catch (Exception e) {
                e.getStackTrace();
            }

        }  else if ("GetVideoRequestParams".equals(id)) {//获取视频讲解请求会与不会状态参数

            try {
                String callbackID = submitEvent.getCallbackId();
                String arg = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(arg);
                int source = -1;
                if (jsonObject.has("source")) {
                    source = jsonObject.getInt("source");
                }
                //2 视频讲解
                if (source == 2 && callbackID != null && productId != null) {
                    GetViedoRequestParms getViedoRequestParms = new GetViedoRequestParms(EApplication.BRAND_ID, productId, cId, classId, subjectId, getUserInfoBase().getUserId() + "");
                    String getViedoRequestParmsCallback = new Gson().toJson(getViedoRequestParms);
                    sendCallBack(callbackID, getViedoRequestParmsCallback);
                }

            } catch (Exception e) {
                e.getStackTrace();
            }

        }

    }

    /**
     * 获取网页展示内容
     *
     * @param path
     */
    private void getResultRes(final String path, final String callBackId) {
        //拿到本地资源回传给H5

        EpaperDao.getInstance().getResource(path, new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void success(final Object data) {
                if (isFinishing()) {
                    return;
                }

                result = data.toString();
                sendCallBack(callBackId, result);
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                showToastError((int) data);
            }
        });
    }

    @Override
    public void finish() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.finish();
        }
    }
}
